package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.goods

import androidx.lifecycle.MutableLiveData
import com.alibaba.fastjson.JSON
import com.example.library_common.db.ShopCarBean
import com.example.library_common.db.UserDatabase
import com.example.library_common.networking.RestClient
import com.example.library_common.networking.RestClientBuilder
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.bean.GoodsDetailBean
import com.example.wallet.db.UserInfoManager

class GoodsNewDetailRepository {

    val user = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

    fun getLocalShopCarBean(): ShopCarBean {
        var mShopCar = ShopCarBean()
        val cache = UserDatabase.getInstance()
            .shopCarBean()
            .getCache(user?.uid)
        if (cache != null) {
            mShopCar = cache
        } else {
            mShopCar.userId = user?.uid
        }
        return mShopCar
    }

    fun getGoodsDetailInfo(mViewModel: GoodsNewDetailViewModel) {

        RestClient.builder()
            .url(R.string.queryGoodsById)
            .raw(
                JSON.toJSONString(
                    mapOf(
                        "goodsId" to mViewModel.mCategoryId,
                        "uid" to user?.uid,
                    )
                )
            ).success {
                val infoDao = JSON.parseObject(it, GoodsDetailBean::class.java)

                val cache = UserDatabase.getInstance()
                    .shopCarBean()
                    .getCache(user?.uid)

                val shopCarList22 = cache?.shopCarList22 ?: emptyList()

                for (e in shopCarList22) {
                    if (infoDao.goods == e) {
                        infoDao.goods = e
                        break
                    }
                }
                mViewModel.collectionLiveData.postValue(infoDao.goods.isCollected)

                mViewModel.infoDaoLiveData.postValue(infoDao)


            }.build()
            .post()

    }

    fun collectionHandle(mViewModel: GoodsNewDetailViewModel) {
        val infoDao = mViewModel.infoDaoLiveData.value
        RestClient.builder()
            .url(R.string.saveOrCancelCollect)
            .raw(
                JSON.toJSONString(
                    mapOf(
                        "goodsId" to infoDao?.goods?.gid,
                        "uid" to user?.uid,
                        "opt" to infoDao?.goods?.toggleCollecting(),
                    )
                )
            )
            .success {
                mViewModel.collectionLiveData.postValue(infoDao?.goods?.isCollected)
//                mViewModel.infoDaoLiveData.postValue(infoDao)
            }
            .build()
            .post()
    }

}